#!/usr/bin  python
# _*_ coding:utf-8 _*_
"""
----------------------------------
    File Name: parents
    Description:
        Author: Dell
        Date: 2020/8/6
-----------------------------------
"""
from rest_framework.views import APIView
from rest_framework.response import Response
from extensions.auth import JwtAuthorizationAuthentication
from Baby import models
from Baby.serializers import parent
from Common.logger import app_log
from Common.response import resp
import datetime


class ParentView(APIView):
    authentication_classes = [JwtAuthorizationAuthentication, ]

    def get(self, request, *args, **kwargs):
        try:
            params = request.query_params
            hospital = params["hospital"]
            group = params["group"]
            if hospital != "ALL":
                if group != "ALL":
                    parent_query = models.Users.objects.filter(hospital=hospital, group=group).all()
                else:
                    parent_query = models.Users.objects.filter(hospital=hospital).all()
            else:
                if group != "ALL":
                    parent_query = models.Users.objects.filter(group=group).all()
                else:
                    parent_query = models.Users.objects.all()
            parent_data = parent.ParentModelSerializer(parent_query, many=True).data
            return Response({
                'error_code': 0,
                'message': "Success",
                'data': parent_data
            })
        except Exception as e:
            app_log.exception(e)
            return resp(-1, e.args)

    def put(self, request, *args, **kwargs):
        try:
            data = request.data
            parent_data = data["parent"]
            hospital = data["hospital"]
            group = data["group"]
            parent_id_list = []
            time_now = datetime.datetime.now()
            email = parent_data["email"]
            parent_id = parent_data.pop("id")
            parent_id_list.append(parent_id)
            parent_db_data = models.Users.objects.filter(email=email).exclude(id=parent_id)
            if parent_db_data.exists():
                return resp(2001, {})
            spouse_id = models.Users.objects.filter(id=parent_id).values("spouse_id").first()
            parent_id_list.append(spouse_id["spouse_id"])
            parent_data["updated_at"] = time_now
            parent_data["full_name"] = "{} {}".format(parent_data["first_name"], parent_data["last_name"])
            models.Users.objects.filter(id=parent_id).update(**parent_data)
            models.Users.objects.filter(id=spouse_id["spouse_id"]).update(hospital=hospital, group=group,
                                                                          updated_at=time_now)
            # 同步一个家庭的hospital、group信息
            one_parent_id = parent_id_list[0]
            baby_id_list = models.UsersBabies.objects.filter(users_id=one_parent_id).values("babies").all()
            for baby_id in baby_id_list:
                models.Babies.objects.filter(id=baby_id["babies"]).update(hospital=hospital, group=group,
                                                                          updated_at=time_now)
            models.UsersBabies.objects.filter(users_id__in=parent_id_list).update(hospital=hospital, group=group,
                                                                                  updated_at=time_now)
            return Response({
                'error_code': 0,
                'message': "Success"
            })
        except Exception as e:
            app_log.exception(e)
            return resp(-1, e.args)

    def delete(self, request, *args, **kwargs):
        try:
            parent_id = request.GET.get("id", "")
            parent_data = models.Users.objects.filter(id=parent_id).all()
            if parent_data.exists():
                models.Users.objects.filter(id=parent_id).delete()
                return Response({
                    'error_code': 0,
                    'message': "Success"
                })
            else:
                return resp(2003, {})
        except Exception as e:
            app_log.exception(e)
            return resp(-1, e.args)
